package com.chatplus.application.service.pay.impl.wechat;

import com.chatplus.application.client.pay.WeChatPayClient;
import com.chatplus.application.client.pay.domain.request.wechat.WeChatOrderPayRequest;
import com.chatplus.application.client.pay.domain.response.wechat.WechatOrderPayResponse;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.enumeration.SubModeEnum;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 微信支付-微信小程序支付
 */
@Service("WeChatApiService_WECHAT_JSAPI")
public class WeChatPayMpPayService extends WeChatPayApiService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(WeChatPayMpPayService.class);

    @Autowired
    public WeChatPayMpPayService(WeChatPayClient weChatPayClient) {
        super(weChatPayClient);
    }

    @Override
    public WechatOrderPayResponse orderPay(WeChatOrderPayRequest param) {
        try {
            WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount();
            WxPayUnifiedOrderV3Request request = new WxPayUnifiedOrderV3Request();
            WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
            // 通知地址
            request.setNotifyUrl(param.getNotifyUrl());
            request.setTimeExpire(param.getExpireTime());

            amount.setTotal(param.getMoney().intValue());
            // 商户订单号
            request.setOutTradeNo(param.getPayTransactionId());
            request.setAmount(amount);
            request.setPayer(payer.setOpenid(param.getUserId()));
            // 商品描述
            request.setDescription(param.getSubject());
            //  附加数据
            request.setAttach(SubModeEnum.WECHAT_JSAPI.getValue());
            request.setMchid(param.getMchId());
            return weChatPayClient.mpPay(request);
        } catch (Exception e) {
            LOGGER.message("微信支付-小程序支付调用失败")
                    .context("request", param)
                    .exception(e).error();
        }
        return null;
    }
}
